#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc, char const *argv[])
{
	int num = 100;

	int pid = fork();

	if (pid > 0)
	{
		printf("father process,pid=%d,ppid=%d\n", getpid(), getppid());
		sleep(3);
		printf(" parent num=%d\n", num);
	}
	else if (pid == 0)
	{
		printf("child process,pid=%d,ppid=%d\n", getpid(), getppid());
		printf("child num=%d\n", num); // 可以继承父进程的值
		num++;

		// 让子进程执行一个ping操作   ping www.baidu.com
		char *exe_path = "/usr/bin/ping";
		char *argv[4] = {"ping", "-c 1000", "www.baidu.com", NULL};
		char *evn[1] = {NULL};
		int ret = execve(exe_path, argv, evn); // 子进程执行execve 替换了子进程原有程序 执行成功结束后不会返回
		if (ret == -1)
		{
			_exit(EXIT_FAILURE); // 子进程退出 使用_exit 不会对主进程影响
		}
	}
	else
	{
		printf("fork error\n");
		exit(EXIT_FAILURE);
	}

	while (1)
	{	
		sleep(5);
		int status;
		int subpid = waitpid(pid, &status, WNOHANG);
		printf("  main process exit ,sub process exit code is %d,pid :%d\n", status, subpid);
	}
	return 0;
}
